package com.github.mofeideyu.jacksonUtil;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * @author Administrator
 * @date 2024/3/29 11:02
 * @description
 */
@Slf4j
public class JacksonXmlUtil {

    private static final XmlMapper xmlMapper = new XmlMapper();
    static {
        //反序列化时，若实体类没有对应的属性，是否抛出JsonMappingException异常，false忽略掉
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //序列化是否绕根元素，true，则以类名为根元素
        xmlMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        //忽略空属性
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    /**
     * 将对象转换位字符串
     * @param objectParam 对象参数
     * @return 对象序列化后对应的xml字符串
     */
    public static String toXmlString(Object objectParam) {
        try {
            return ObjectUtils.isEmpty(objectParam) ? null : xmlMapper.writeValueAsString(objectParam);
        } catch (Exception e) {
            log.error("对象转xmlString失败: {}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 将xmlString格式的数据转换为指定类型的对象
     * @param param xmlString
     * @param klass xml内容对应要转换的类型
     * @return 指定类型的对象
     * @param <T> klass
     */
    public static <T> T parseObject(String param, Class<T> klass) {
        try {
            return StringUtils.hasText(param) ? xmlMapper.readValue(param, klass) : null;
        } catch (JsonProcessingException e) {
            log.error("xmlString转对象失败: {}", e.getMessage(), e);
        }
        return null;
    }


}
